package cn.com.ahao.gateway.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import static org.springframework.cloud.gateway.filter.NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER;

@Component
public class DurationStatisticsFilter implements GlobalFilter, Ordered {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        logger.info("====== DurationStatisticsFilter start ======");
        exchange.getAttributes().put("durationStart", System.currentTimeMillis());

        return chain.filter(exchange).doFinally(f -> printDurationTime(exchange));
    }

    private void printDurationTime(ServerWebExchange exchange) {
        long start = exchange.getAttribute("durationStart");
        long end = System.currentTimeMillis();
        logger.info("====== DurationStatisticsFilter end, cost: {} ======", (end - start));
    }

    @Override
    public int getOrder() {
        return WRITE_RESPONSE_FILTER_ORDER - 1;
    }
}
